//
//  DXViewController.m
//  XDWatermarkDemo
//
//  Created by xieyajie on 13-7-26.
//  Copyright (c) 2013年 xieyajie. All rights reserved.
//

#import "WMCViewController.h"

#import <ImageIO/ImageIO.h>
#import "LeveyTabBarController.h"
#import "BanBu_LabelViewController.h"
#import "BanBu_WatermarkView.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_NavigationController.h"
#import "BanBu_NavButton.h"
#import "BanBu_LocationManager.h"
#import "BanBu_ThemeManager.h"

@interface WMCViewController ()
{
    AVCaptureSession *_session;
    AVCaptureDeviceInput *_captureInput;
    AVCaptureStillImageOutput *_captureOutput;
    AVCaptureVideoPreviewLayer *_preview;
    AVCaptureDevice *_device;
    
    UIImage *_finishImage;
}

@end

@implementation WMCViewController

@synthesize cameraView = _cameraView;
@synthesize takePhotoButton = _takePhotoButton;
@synthesize watermarkScroll = _watermarkScroll;
@synthesize flashButton = _flashButton;
@synthesize positionButton = _positionButton;

@synthesize saveButton = _saveButton;
@synthesize cancelButton = _cancelButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    self.navigationController.navigationBarHidden = YES;
    
    ThemeManager.watermarkController = self;
    
    //初始化摄像头
    [self initialize];
    
    if (!IS_IOS_7)
    {
        self.cameraView.frame = CGRectMake(0, 50, 320, 416);
    }
    
    _preview = [AVCaptureVideoPreviewLayer layerWithSession: _session];
    _preview.frame = CGRectMake(0, 0, self.cameraView.frame.size.width, self.cameraView.frame.size.height);
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self.cameraView.layer addSublayer:_preview];
     [_session startRunning];
    
    [self initWaterScroll];
    
    //获取天气
    [self getWeather];
}

- (void)viewDidAppear:(BOOL)animated
{
    ThemeManager.watermarkController = self;
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
//    [self addHollowOpenToView:self.cameraView];
}

- (void)viewDidUnload
{
    [self setWatermarkPage:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    ThemeManager.watermarkController = nil;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    ThemeManager.watermarkController = nil;
    [_watermarkView release],_watermarkView = nil;
    
    [_session release],_session = nil;
    [_finishImage release],_finishImage = nil;
    [_captureOutput release],_captureOutput = nil;
    
    [_cameraView release],_cameraView = nil;
    [_cancelButton release],_cancelButton = nil;
    [_takePhotoButton release],_takePhotoButton = nil;
    [_saveButton release],_saveButton = nil;
    [_positionButton release],_positionButton = nil;
    [_flashButton release],_flashButton = nil;
    [_watermarkScroll release],_watermarkScroll = nil;
    [_watermarkPage release],_watermarkPage = nil;
    [super dealloc];
}

#pragma mark - private

- (void) initialize
{
    //1.创建会话层
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPreset640x480];
    
    //2.创建、配置输入设备
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [_device lockForConfiguration:nil];
    if([_device flashMode] == AVCaptureFlashModeOff){
        [_flashButton setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
    }
    else if([_device flashMode] == AVCaptureFlashModeAuto){
        [_flashButton setImage:[UIImage imageNamed:@"flash-auto.png"] forState:UIControlStateNormal];
    }
    else{
        [_flashButton setImage:[UIImage imageNamed:@"flash.png"] forState:UIControlStateNormal];
    }
    [_device unlockForConfiguration];

	NSError *error;
	_captureInput = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
	if (!_captureInput)
	{
		NSLog(@"Error: %@", error);
		return;
	}
    [_session addInput:_captureInput];
    
    
    //3.创建、配置输出
    _captureOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [_captureOutput setOutputSettings:outputSettings];
	[_session addOutput:_captureOutput];
}

- (void)initWaterScroll
{
    _watermarkScroll = [[UIScrollView alloc] initWithFrame:self.cameraView.frame];
    _watermarkScroll.showsHorizontalScrollIndicator = NO;
    
    _watermarkScroll.pagingEnabled = YES;
    _watermarkScroll.delegate = self;
    
    [self createWatermarkImageView];
    
    self.watermarkPage.numberOfPages = 4;
    self.watermarkPage.currentPage = 0;
    [self.view bringSubviewToFront:self.watermarkPage];
    [self.view addSubview:_watermarkScroll];
}

-(void)createWatermarkImageView
{
    //根据图片距离的属性设置textLabel的显示和事件；
    CGFloat width = 320;
    
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"watermark"];
    NSString * infoPath = [fileName stringByAppendingPathComponent:@"kindinfo.plist"];
    NSDictionary * infoDic = [NSDictionary dictionaryWithContentsOfFile:infoPath];
    
    _watermarkScroll.contentSize = CGSizeMake(320 * infoDic.count, _watermarkScroll.frame.size.height);
    
    int i = 0;
    for (NSString * folderName in infoDic.allKeys)
    {
        if (i >= infoDic.count)
        {
            break;
        }
        //创建ImageView
        BanBu_WatermarkView * watermarkView = [[BanBu_WatermarkView alloc]init];
        watermarkView.frame = CGRectMake(i * width, 0, 128, 128+35);
        watermarkView.userInteractionEnabled = YES;
        watermarkView.tag = i+1;
        watermarkView.folderName = folderName;
        
        //初始化图片
        [watermarkView initWithImageView:CGRectMake(0, 0, 128, 128)];
        
        //初始化文本
        CGRect frame = CGRectMake(0, 128, 100, 35);
        [watermarkView initWithText1: frame];
        
        //设置图片
        NSString * imageName = [[fileName stringByAppendingPathComponent: folderName] stringByAppendingPathComponent:VALUE(folderName, infoDic)];
        watermarkView.imagePath = imageName;
        watermarkView.imageView.image = [UIImage imageWithContentsOfFile:imageName];
        
        //设置文本
        NSString * textPath = [[fileName stringByAppendingPathComponent: folderName] stringByAppendingPathComponent:@"watermark-text.plist"];
        NSDictionary * textDic = [NSDictionary dictionaryWithContentsOfFile:textPath];
        watermarkView.textLabel1.text = [textDic.allValues objectAtIndex:0];

        //添加手势
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGesture:)];
        pan.maximumNumberOfTouches = 2;
        pan.minimumNumberOfTouches = 1;
        
        [watermarkView addGestureRecognizer:pan];
        [pan release];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
        [watermarkView.imageView addGestureRecognizer:tap];
        [tap release];
        
        UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textTap:)];
        [watermarkView.textLabel1 addGestureRecognizer:tap2];
        [tap2 release];
        
        [_watermarkScroll addSubview:watermarkView];
        
        if (!i)
        {
            self.watermarkView = watermarkView;
        }
        
        i++;
        [watermarkView release];
    }
}

#pragma mark - 手势
//平移
-(void)panGesture:(UIPanGestureRecognizer *)sender
{
    self.watermarkView =(BanBu_WatermarkView *)sender.view;
    
    CGPoint point = [sender translationInView:self.view];
    
    if (point.x == point.y && point.x == 0)
    {
        return;
    }
    
    CGAffineTransform transform = CGAffineTransformMakeTranslation(point.x,point.y);
    
    if (self.trans.tx || self.trans.ty)
    {
        transform = CGAffineTransformConcat(transform, self.trans);
    }
    
    if (sender.state == UIGestureRecognizerStateBegan)
    {
        self.watermarkView.alpha = 0.7;
    }
    else if (sender.state == UIGestureRecognizerStateEnded)
    {
        self.enable = NO;
        self.watermarkView.alpha = 1;
        self.trans = transform;
        self.watermarkView.trans = transform;
    }
    
    [self.watermarkView setTransform:transform];
    
    //查看是否需要重新调整
    [self changeFrame];
}

//点击文本
- (void)textTap:(UITapGestureRecognizer *)sender
{
    BanBu_LabelViewController * labelController = [[BanBu_LabelViewController alloc]init];
    labelController.delegate = self;
    labelController.folderName = self.watermarkView.folderName;
    labelController.title =  self.watermarkView.folderName;
    BanBu_NavigationController * nav = [[BanBu_NavigationController alloc]initWithRootViewController:labelController];
    
    [self.navigationController presentModalViewController:nav animated:YES];
    [nav release];
    [labelController release];
}

//点击图片
-(void)imageTap:(UITapGestureRecognizer *)sneder
{
    BanBu_ImageTableController * imageTable = [[BanBu_ImageTableController alloc]init];
    imageTable.delegate = self;
    imageTable.folderName = self.watermarkView.folderName;
    imageTable.title = self.watermarkView.folderName;
    BanBu_NavigationController * nav = [[BanBu_NavigationController alloc]initWithRootViewController:imageTable];

    [self.navigationController presentModalViewController:nav animated:YES];
    [nav release];
    [imageTable release];
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.watermarkPage.currentPage = scrollView.contentOffset.x/320.0;
    self.watermarkView = (BanBu_WatermarkView *)[scrollView viewWithTag:self.watermarkPage.currentPage+1];
    self.trans = self.watermarkView.trans;
    if ([self.watermarkView.folderName isEqualToString:@"weather"])//当界面为天气时，设置天气
    {
        self.watermarkView.textLabel1.text = [self.weatherDic valueForKey:@"temp"];
    }
}

#pragma mark - labelViewDelegate
-(void)didSelectedRowIn:(BanBu_LabelViewController *)labelView atIndexPath:(NSIndexPath *)indexPath
{
    self.watermarkView.textLabel1.text = [labelView.labelArray objectAtIndex:indexPath.row];
    [labelView.navigationController dismissModalViewControllerAnimated:YES];
}

#pragma mark - imageTableDelegate
-(void)didSelectedImage:(UIImage *)image andImagePath:(NSString *)imagePath andController:(BanBu_ImageTableController *)imageTableController
{
    self.watermarkView.imageView.image = image;
    self.watermarkView.imagePath = imagePath;
    [imageTableController dismissModalViewControllerAnimated:YES];
}

//查看是否需要重新调整
-(void)changeFrame
{
    CGRect rect = self.watermarkView.frame;
    CGPoint point2 = self.watermarkView.frame.origin;
    
    BOOL bl = NO;
    if (rect.origin.x<=0)
    {
        point2.x = 0;
        bl = YES;
    }
    else if (rect.origin.x <= 320*self.watermarkPage.currentPage)
    {
        point2.x = 320*self.watermarkPage.currentPage;
        bl = YES;
    }
    else if(rect.origin.x+rect.size.width >= 320*(self.watermarkPage.currentPage +1))
    {
        point2.x = 320*(self.watermarkPage.currentPage +1)-self.watermarkView.frame.size.width;
        bl = YES;
    }
    
    if (rect.origin.y<=0)
    {
        point2.y = 0;
        bl = YES;
    }
    else if(rect.origin.y+rect.size.height >= 416)
    {
        point2.y = 416-self.watermarkView.frame.size.height;
        bl = YES;
    }
    
    if (bl)
    {
        self.watermarkView.frame = CGRectMake(point2.x, point2.y, self.watermarkView.bounds.size.width, self.watermarkView.bounds.size.height);
    }
}

//获取本地天气
-(void)getWeather
{
    NSMutableDictionary * parDic = [[NSMutableDictionary alloc]initWithCapacity:5];
    //获取到经纬度信息
    [parDic setValue:[NSNumber numberWithDouble:(NSInteger)(AppLocationManager.curLocation.longitude*1000000)] forKey:@"plong"];
    [parDic setValue:[NSNumber numberWithDouble:(NSInteger)(AppLocationManager.curLocation.latitude*1000000)] forKey:@"plat"];

//    [AppComManager getBanBuData:BanBu_Get_Weather par:parDic delegate:self];
}

#pragma mark -

- (void)addHollowOpenToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5f;
    animation.delegate = self;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = @"cameraIrisHollowOpen";
    [view.layer addAnimation:animation forKey:@"animation"];
}

- (void)addHollowCloseToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];//初始化动画
    animation.duration = 0.5f;//间隔的时间
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"cameraIrisHollowClose";
    
    [view.layer addAnimation:animation forKey:@"HollowClose"];
}

#pragma mark - IBAction

//返回上级界面
- (IBAction)cancelTakePhoto:(UIButton *)sender
{
    ThemeManager.watermarkController = nil;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

//拍照
- (IBAction)takePhoto:(id)sender
{
    if (_finishImage)
    {
        return;
    }
    
    [self addHollowCloseToView:self.cameraView];
    
    //get connection
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in _captureOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }
    
    //get UIImage
    [_captureOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
                                                    _saveButton.hidden = NO;
                                                    _cancelButton.hidden = NO;
                                                    [self addHollowCloseToView:self.cameraView];
                                                    [_session stopRunning];
                                                    [self addHollowOpenToView:self.cameraView];
                                                    
                                                    NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
                                                    _finishImage = [[UIImage alloc] initWithData:imageData] ;
                                                }];
}

//闪光灯设置
- (IBAction)changeFlash:(id)sender
{
    if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && [_device hasFlash])
    {
        [_flashButton setEnabled:NO];
        [_device lockForConfiguration:nil];
        if([_device flashMode] == AVCaptureFlashModeOff)
        {
            [_device setFlashMode:AVCaptureFlashModeAuto];
            [_flashButton setImage:[UIImage imageNamed:@"flash-auto.png"] forState:UIControlStateNormal];
        }
        else if([_device flashMode] == AVCaptureFlashModeAuto)
        {
            [_device setFlashMode:AVCaptureFlashModeOn];
            [_flashButton setImage:[UIImage imageNamed:@"flash.png"] forState:UIControlStateNormal];
        }
        else{
            [_device setFlashMode:AVCaptureFlashModeOff];
            [_flashButton setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
        }
        [_device unlockForConfiguration];
        [_flashButton setEnabled:YES];
    }
}

//切换前后镜头
- (IBAction)positionCnange:(id)sender
{
    //添加动画
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = .8f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"oglFlip";
    if (_device.position == AVCaptureDevicePositionFront) {
        animation.subtype = kCATransitionFromRight;
    }
    else if(_device.position == AVCaptureDevicePositionBack){
        animation.subtype = kCATransitionFromLeft;
    }
    [_preview addAnimation:animation forKey:@"animation"];
    
    NSArray *inputs = _session.inputs;
    for ( AVCaptureDeviceInput *input in inputs )
    {
        AVCaptureDevice *device = input.device;
        if ([device hasMediaType:AVMediaTypeVideo])
        {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera = nil;
            AVCaptureDeviceInput *newInput = nil;
            
            if (position == AVCaptureDevicePositionFront)
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            }
            else
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            }
            _device = newCamera;
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            
            // beginConfiguration ensures that pending changes are not applied immediately
            [_session beginConfiguration];
            
            [_session removeInput:input];
            [_session addInput:newInput];
            
            // Changes take effect once the outermost commitConfiguration is invoked.
            [_session commitConfiguration];
            break;
        }
    }
}

//切换镜头
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == position)
        {
            return device;
        }
    }
    return nil;
}

//保存图片
- (IBAction)saveAction:(id)sender
{
    UIImage *image = _finishImage;
    NSString * imageName = self.watermarkView.imagePath;
    UIImage *waterImage = [UIImage imageWithContentsOfFile:imageName];
    
    _finishImage = [self composeImage:waterImage toImage:image atFrame:self.watermarkView.imageView.frame];
    
    UIImageWriteToSavedPhotosAlbum(_finishImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    _saveButton.hidden = YES;
    _cancelButton.hidden = YES;
    [_session startRunning];
}

//合并两张图
- (UIImage *)composeImage:(UIImage *)subImage toImage:(UIImage *)superImage atFrame:(CGRect)frame
{
    CGSize superSize = superImage.size;
//    superSize.height /=2;
//    superSize.width /=2;
    
    CGFloat widthScale = frame.size.width / self.cameraView.frame.size.width;
    CGFloat heightScale = frame.size.height / self.cameraView.frame.size.height;
    
    CGFloat x = (int)frame.origin.x % 320;
    
    CGRect subFrame = CGRectMake(x, frame.origin.y, widthScale * superSize.width, heightScale * superSize.height);
    
    UIGraphicsBeginImageContext(superSize);
    [superImage drawInRect:CGRectMake(0, 0, superSize.width, superSize.height)];
    [subImage drawInRect:subFrame];
    
    CGPoint point = CGPointMake(subFrame.origin.x, subFrame.origin.y+subFrame.size.height);
    [self.watermarkView.textLabel1.text drawAtPoint:point withFont:[UIFont systemFontOfSize:14]];

    __autoreleasing UIImage *finish = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return finish;
}

//保存后操作
-(void) image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    // Was there an error?
    if (error != NULL)
    {
        // Show error message…
        NSLog(@"save error");
        _finishImage= nil;
        [self cancelAction:nil];
    }
    else  // No errors
    {
        // Show message image successfully saved
        NSLog(@"save success");
        _finishImage= nil;
    }
}

- (IBAction)cancelAction:(id)sender
{
    _finishImage = nil;
    _saveButton.hidden = YES;
    _cancelButton.hidden = YES;
    [_session startRunning];
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
//    if ([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Weather])
//    {
////        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[VALUE(@"weather", resDic) valueForKey:@"temp"] activityAnimated:YES];
//        self.weatherDic = [resDic valueForKey:@"weather"];
//    }
}


@end
